//
//  ByTabBar.m
//  mijifen_ios
//
//  Created by 朱凯 on 2017/10/10.
//  Copyright © 2017年 itboye. All rights reserved.
//

#import "ByTabBar.h"

@implementation ByTabBar
{
    UIControl *_selectedView;       // 当前选中的barview
    
    NSInteger _count;
    UILabel *_notifyMarkLabel;      // 用于提示用户有新消息（通过通知）
}

- (instancetype)init {
    
    if (self = [super init]) {
        
//        self.backgroundColor = [UIColor colorWithWhite:0.96 alpha:1];
        self.backgroundColor = [UIColor whiteColor];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifyMarkDidModify:) name:KTabBarNotifyMarkModifyNotificationName object:nil];
    }
    return self;
}

#pragma mark - 更新约束
- (void)updateConstraints {
    
    NSLog(@"tabbar 更新约束,%@", NSStringFromCGRect(self.frame));
    [super updateConstraints];
}

#pragma mark - 通知
- (void)notifyMarkDidModify:(NSNotification *)notifitcation {
    
    NSDictionary *userInfo = notifitcation.userInfo;
    NSInteger index = [userInfo[KTabBarNotifyMarkModifyNotificationIndexKey] integerValue];
    NSInteger badge = [userInfo[KTabBarNotifyMarkModifyNotificationBadgeKey] integerValue];
    CGFloat width = 10;
    CGFloat height = 10;
    if (badge > 0) {
        NSString *text = [NSString stringWithFormat:@"%li", badge];
        width = [text getSizeOfString:10].width + 10;
        _notifyMarkLabel.text = text;
    } else if (badge == 0) {
        width = 0;
    } else {
        //
    }
    [_notifyMarkLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(width, height));
        make.top.equalTo(self).offset(10);
        make.right.equalTo(self).multipliedBy(1.0 / _count * (index + 1));
    }];
}

#pragma mark - getter
- (UIColor *)tintColor {
    
    if (!_tintColor) {
        _tintColor = [UIColor blackColor];
    }
    return _tintColor;
}
- (UIColor *)highlightTintColor {
    
    if (!_highlightTintColor) {
        _highlightTintColor = BY_TEXT_COLOR;
    }
    return _highlightTintColor;
}

#pragma mark - setter

#pragma mark - setupUI
#define KTabBarSubviewBaseTag 100
- (void)setupUI {
    
    NSAssert(_images.count == _highlightImages.count, @"常态图片数量必须和高亮图片数量一致");
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    
    // 顶部线条
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    [self addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self).insets(UIEdgeInsetsZero).priorityMedium();
        make.height.mas_equalTo(1);
    }];
    
    // 角标label
    _notifyMarkLabel = [[UILabel alloc] init];
    _notifyMarkLabel.backgroundColor = [UIColor redColor];
    _notifyMarkLabel.adjustsFontSizeToFitWidth = true;
    _notifyMarkLabel.numberOfLines = 1;
    _notifyMarkLabel.text = @"";
    _notifyMarkLabel.font = FONT(10);
    _notifyMarkLabel.textAlignment = NSTextAlignmentCenter;
    _notifyMarkLabel.textColor = [UIColor whiteColor];
    _notifyMarkLabel.layer.cornerRadius = 5;
    _notifyMarkLabel.layer.masksToBounds = true;
    [self addSubview:_notifyMarkLabel];
    
    NSInteger count = MAX(_titles.count, _images.count);
    _count = count;
    NSInteger limit = MIN(_titles.count, _images.count);
    UIView *lastView;
    for (int i = 0; i < count; i ++) {
        
        UIControl *view = [[UIControl alloc] init];
        view.tag = KTabBarSubviewBaseTag + i;
        [view addTarget:self action:@selector(touchAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self);
            if (i == 0) {
                make.left.equalTo(self);
            } else {
                make.left.equalTo(lastView.mas_right);
            }
            make.width.equalTo(self).multipliedBy(1.0 / count);
            make.height.equalTo(self);
        }];
        lastView = view;
        
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.tag = 1;
        [view addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] init];
        label.tag = 2;
        label.adjustsFontSizeToFitWidth = true;
        label.numberOfLines = 1;
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = self.tintColor;
        [view addSubview:label];
    
        if (i < limit) {
            imageView.image = [UIImage imageNamed:_images[i]];
            label.text = _titles[i];
            [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.mas_equalTo(CGSizeMake(25, 25));
                make.centerX.equalTo(view);
                make.top.equalTo(view).offset(4);
            }];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(view).insets(UIEdgeInsetsMake(0, 0, 0, 0)).priorityMedium();
                make.top.equalTo(imageView.mas_bottom);
            }];
        } else {
            // 图片少于文字
            if (_titles.count > limit) {
                label.text = _titles[i];
                [label mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.edges.equalTo(view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
                }];
            }
            // 图片多于文字
            else {
                imageView.image = [UIImage imageNamed:_images[i]];
                [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.size.mas_equalTo(CGSizeMake(25, 25));
                    make.centerX.equalTo(view);
                    make.centerY.equalTo(view);
                }];
            }
        }
        
        
        if (i == 0) {
            [self touchAction:view];
        }
    }
    
}



#pragma mark - 点击事件
- (void)touchAction:(UIControl *)sender {
    // 第一次点击
    if (_selectedView == nil) {
        _selectedView = sender;
        [self setViewHighlight:true view:sender];
        return;
    }
    
    // 点击同一个
    if (_selectedView == sender) {
        return;
    }
    NSLog(@"%ld",_selectIndex);
    /***判断是否登录*/
    if ((sender.tag - KTabBarSubviewBaseTag) == 1) {
        ByModelUser *user = [ByCacheUser getUserInfo];
        if (!user.uid) {
            ByLoginVC *loginVC = [[ByLoginVC alloc] init];
            loginVC.typeFrom = @"1";
            ByBaseNaviController *navi = [[ByBaseNaviController alloc] initWithRootViewController:loginVC];
            [self.viewController presentViewController:navi animated:YES completion:nil];
            return;
        }
    }
    [self setViewHighlight:true view:sender];
    [self setViewHighlight:false view:_selectedView];

    _selectIndex = sender.tag - KTabBarSubviewBaseTag;
    _selectedView = sender;
    
    if (_selectBlock) {
        _selectBlock(_selectIndex);
    }
    
}

- (void)setViewHighlight:(BOOL)highlight view:(UIControl *)view {
    
    UIImageView *imageView = [view viewWithTag:1];
    UILabel *label = [view viewWithTag:2];
    
    NSInteger tag = view.tag - KTabBarSubviewBaseTag;
    if (highlight) {
        NSInteger index = MIN(_highlightImages.count - 1, tag);
        imageView.image = [UIImage imageNamed:_highlightImages[index]];
        label.textColor = self.highlightTintColor;
    } else {
        NSInteger index = MIN(_images.count - 1, tag);
        imageView.image = [UIImage imageNamed:_images[index]];
        label.textColor = self.tintColor;
    }
}
@end
